const CryptoJS = require('crypto-js') // 引用AES源码js

const key = CryptoJS.enc.Utf8.parse('9ouxQY9ALwFhQaFj') // 十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('FQFBCcQh59HNFr2M') // 十六位十六进制数作为密钥偏移量

function judgeIsAnyNullStr() {
  if (arguments.length > 0) {
    for (var i = 0; i < arguments.length; i++) {
      if (arguments[i] == null || arguments[i] === '' || arguments[i] === undefined || arguments[i] === 'undefined' || arguments[i] === '未设置') {
        return true
      }
    }
  }
  return false
}

// 加密方法
export function encrypt(word) {
  const userInfo = JSON.parse(localStorage.getItem('user_info'))

  word = JSON.stringify(word)
  const srcs = CryptoJS.enc.Utf8.parse(word)
  if (userInfo && !judgeIsAnyNullStr(userInfo.secret)) {
    const encrypted = CryptoJS.AES.encrypt(srcs, CryptoJS.enc.Utf8.parse(userInfo.secret), {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.toString()
  } else {
    const encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.toString()
  }
}

// 解密方法
export function decrypt(word) {
  var userInfo = JSON.parse(localStorage.getItem('user_info'))

  let decrypted = null
  if (userInfo && !judgeIsAnyNullStr(userInfo.secret)) {
    decrypted = CryptoJS.AES.decrypt(word, CryptoJS.enc.Utf8.parse(userInfo.secret), {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
  } else {
    decrypted = CryptoJS.AES.decrypt(word, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
  }
  return decrypted.toString(CryptoJS.enc.Utf8)
}

export default {
  decrypt,
  encrypt
}
